#include <iostream>
using namespace std;
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{
    // 处理argc， argv[]
    if (argc != 3)
    {
        cout << "has return " << endl;
        return 1;
    }
    //
    uint16_t serverport = stoi(argv[2]);
    string serverip = argv[1];

    // 创建addr结构体， 设置端口号ip地址
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        cout << "socket error" << endl;
        return 1;
    }
    sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

    // 1、客户端要绑定端口号， 但是不需要显示的绑定， 而是系统进行随机端口的绑定。
    int n = connect(sockfd, (sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        cerr << "connect error..." << endl;
        return 2;
    }

    // 2、发送信息， 接收信息。
    string message;
    while (true)
    {
        cout << "Please Enter# ";
        getline(cin, message);

        //
        write(sockfd, message.c_str(), message.size());

        char inbuffer[4096];
        int n = read(sockfd, inbuffer, sizeof(inbuffer) - 1);
        if (n > 0)
        {
            inbuffer[n] = 0;
            cout << inbuffer << endl;
        }
    }

    return 0;
}